<template>
  <div class="orders-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>体验订单</span>
          <el-button type="success" @click="exportData">导出数据</el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" />
        </el-form-item>
        <el-form-item label="体验项目">
          <el-input
            v-model="searchForm.experience"
            placeholder="请输入项目名称"
          />
        </el-form-item>
        <el-form-item label="预约人">
          <el-input v-model="searchForm.customer" placeholder="请输入预约人" />
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态">
            <el-option label="待支付" value="pending" />
            <el-option label="已支付" value="paid" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="已退款" value="refunded" />
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        :data="sortedTableData"
        v-loading="loading"
        style="width: 100%"
        @sort-change="handleSortChange"
      >
        <template #empty>
          <div class="empty-state">
            <el-empty 
              description="暂无订单数据" 
              :image-size="200"
            >
              <div class="empty-text">还没有收到任何体验订单</div>
              <div class="empty-subtext">当用户预订体验项目后，订单会显示在这里</div>
            </el-empty>
          </div>
        </template>
        <el-table-column
          prop="orderNo"
          label="订单号"
          width="180"
          sortable="custom"
        />
        <el-table-column label="体验项目" min-width="300">
          <template #default="{ row }">
            <div class="experience-info">
              <el-image
                :src="row.experience.cover"
                :preview-src-list="[row.experience.cover]"
                class="experience-image"
                fit="cover"
              />
              <div class="experience-detail">
                <h3 class="experience-title">{{ row.experience.title }}</h3>
                <p class="experience-time">预约时间：{{ row.bookingTime }}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="预约信息" width="200">
          <template #default="{ row }">
            <div>预约人：{{ row.customer.name }}</div>
            <div>手机：{{ row.customer.phone }}</div>
            <div>人数：{{ row.quantity }}人</div>
          </template>
        </el-table-column>
        <el-table-column
          prop="amount"
          label="订单金额"
          width="120"
          sortable="custom"
        >
          <template #default="{ row }">
            <span>¥{{ row.amount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="订单状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="下单时间"
          width="180"
          sortable="custom"
        />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" size="small" @click="handleDetail(row)"
                >详情</el-button
              >
              <el-button
                v-if="row.status === 'pending'"
                type="danger"
                size="small"
                @click="handleCancel(row)"
              >
                取消
              </el-button>
              <el-button
                v-if="row.status === 'paid'"
                type="success"
                size="small"
                @click="handleComplete(row)"
              >
                完成
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 订单详情对话框 -->
      <el-dialog v-model="detailVisible" title="订单详情" width="700px">
        <div v-if="currentOrder" class="order-detail">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="订单号" :span="2">{{
              currentOrder.orderNo
            }}</el-descriptions-item>
            <el-descriptions-item label="体验项目" :span="2">{{
              currentOrder.experience.title
            }}</el-descriptions-item>
            <el-descriptions-item label="预约时间">{{
              currentOrder.bookingTime
            }}</el-descriptions-item>
            <el-descriptions-item label="预约人数"
              >{{ currentOrder.quantity }}人</el-descriptions-item
            >
            <el-descriptions-item label="订单状态">
              <el-tag :type="getStatusType(currentOrder.status)">
                {{ getStatusText(currentOrder.status) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="订单金额"
              >¥{{ currentOrder.amount }}</el-descriptions-item
            >
            <el-descriptions-item label="预约人">{{
              currentOrder.customer.name
            }}</el-descriptions-item>
            <el-descriptions-item label="联系电话">{{
              currentOrder.customer.phone
            }}</el-descriptions-item>
            <el-descriptions-item label="下单时间">{{
              currentOrder.createTime
            }}</el-descriptions-item>
            <el-descriptions-item label="支付时间">{{
              currentOrder.payTime || "-"
            }}</el-descriptions-item>
            <el-descriptions-item label="备注信息" :span="2">{{
              currentOrder.remark || "无"
            }}</el-descriptions-item>
          </el-descriptions>

          <div class="detail-footer">
            <el-button @click="detailVisible = false">关闭</el-button>
            <el-button
              v-if="currentOrder.status === 'pending'"
              type="danger"
              @click="handleCancel(currentOrder)"
            >
              取消订单
            </el-button>
            <el-button
              v-if="currentOrder.status === 'paid'"
              type="success"
              @click="handleComplete(currentOrder)"
            >
              完成订单
            </el-button>
          </div>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import service from "@/api/axios";
import * as XLSX from 'xlsx';

// 搜索表单
const searchForm = reactive({
  orderNo: "",
  experience: "",
  customer: "",
  status: "",
  dateRange: [],
});

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 表格数据
const tableData = ref([]);
const loading = ref(false);

// 详情对话框
const detailVisible = ref(false);
const currentOrder = ref(null);

// 排序相关
const sortConfig = reactive({
  prop: "",
  order: "",
});

// 获取排序后的表格数据
const sortedTableData = computed(() => {
  const list = [...tableData.value];
  if (!sortConfig.prop) return list;

  return list.sort((a, b) => {
    let aValue = a[sortConfig.prop];
    let bValue = b[sortConfig.prop];

    // 处理数字类型
    if (["amount", "quantity"].includes(sortConfig.prop)) {
      aValue = Number(aValue);
      bValue = Number(bValue);
    }

    // 处理日期类型
    if (["createTime", "bookingTime"].includes(sortConfig.prop)) {
      aValue = new Date(aValue).getTime();
      bValue = new Date(bValue).getTime();
    }

    if (sortConfig.order === "ascending") {
      return aValue > bValue ? 1 : -1;
    } else {
      return aValue < bValue ? 1 : -1;
    }
  });
});

// 处理排序变化
const handleSortChange = ({ prop, order }) => {
  sortConfig.prop = prop;
  sortConfig.order = order;
};

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    pending: "warning",
    paid: "primary",
    completed: "success",
    cancelled: "info",
    refunded: "danger",
  };
  return types[status] || "info";
};

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    pending: "待支付",
    paid: "已支付",
    completed: "已完成",
    cancelled: "已取消",
    refunded: "已退款",
  };
  return texts[status] || status;
};

// 获取订单列表
const fetchData = async () => {
  loading.value = true;
  try {
    // 构建请求参数
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      orderNo: searchForm.orderNo,
      experienceName: searchForm.experience,
      customerName: searchForm.customer,
      status: searchForm.status,
      startDate: searchForm.dateRange && searchForm.dateRange[0] ? searchForm.dateRange[0] : null,
      endDate: searchForm.dateRange && searchForm.dateRange[1] ? searchForm.dateRange[1] : null,
      sort: sortConfig.prop,
      order: sortConfig.order
    };
    
    const res = await service.get('/admin/experiences/orders', { params });
    
    if (res.code === 200 && res.data) {
      // 处理API返回的数据
      const list = res.data.list || [];
      
      // 转换数据格式
      tableData.value = list.map(item => {
        return {
          orderNo: item.orderNo,
          experience: {
            id: item.experienceId,
            title: item.experienceTitle,
            cover: item.experienceCover || 'https://example.com/default-cover.jpg'
          },
          customer: {
            name: item.userName,
            phone: item.userPhone
          },
          bookingTime: item.bookingTime,
          quantity: item.quantity,
          amount: item.amount,
          status: item.status,
          createTime: item.createTime,
          payTime: item.payTime,
          remark: item.notes
        };
      });
      
      total.value = res.data.total || 0;
    } else {
      // 使用测试数据
      tableData.value = [
        {
          orderNo: "EXP202403010001",
          experience: {
            title: "贵港传统手工艺体验",
            cover: "https://example.com/image1.jpg",
          },
          customer: {
            name: "张三",
            phone: "13800138000",
          },
          bookingTime: "2024-03-15 14:00",
          quantity: 2,
          amount: 176,
          status: "paid",
          createTime: "2024-03-01 10:00:00",
          payTime: "2024-03-01 10:05:00",
          remark: "需要准备工具",
        },
        {
          orderNo: "EXP202403010002",
          experience: {
            title: "壮族特色美食制作体验",
            cover: "https://example.com/image2.jpg",
          },
          customer: {
            name: "李四",
            phone: "13900139000",
          },
          bookingTime: "2024-03-16 09:00",
          quantity: 3,
          amount: 360,
          status: "pending",
          createTime: "2024-03-01 11:30:00",
          payTime: null,
          remark: "",
        },
        {
          orderNo: "EXP202403010003",
          experience: {
            title: "贵港水乡农事体验",
            cover: "https://example.com/image3.jpg",
          },
          customer: {
            name: "王五",
            phone: "13700137000",
          },
          bookingTime: "2024-03-14 10:00",
          quantity: 1,
          amount: 75,
          status: "completed",
          createTime: "2024-03-01 14:20:00",
          payTime: "2024-03-01 14:25:00",
          remark: "希望有专人指导",
        },
      ];
      total.value = 3;
    }
  } catch (error) {
    console.error("获取订单列表失败", error);
    // 使用测试数据
    tableData.value = [
      {
        orderNo: "EXP202403010001",
        experience: {
          title: "贵港传统手工艺体验",
          cover: "https://example.com/image1.jpg",
        },
        customer: {
          name: "张三",
          phone: "13800138000",
        },
        bookingTime: "2024-03-15 14:00",
        quantity: 2,
        amount: 176,
        status: "paid",
        createTime: "2024-03-01 10:00:00",
        payTime: "2024-03-01 10:05:00",
        remark: "需要准备工具",
      },
      {
        orderNo: "EXP202403010002",
        experience: {
          title: "壮族特色美食制作体验",
          cover: "https://example.com/image2.jpg",
        },
        customer: {
          name: "李四",
          phone: "13900139000",
        },
        bookingTime: "2024-03-16 09:00",
        quantity: 3,
        amount: 360,
        status: "pending",
        createTime: "2024-03-01 11:30:00",
        payTime: null,
        remark: "",
      },
      {
        orderNo: "EXP202403010003",
        experience: {
          title: "贵港水乡农事体验",
          cover: "https://example.com/image3.jpg",
        },
        customer: {
          name: "王五",
          phone: "13700137000",
        },
        bookingTime: "2024-03-14 10:00",
        quantity: 1,
        amount: 75,
        status: "completed",
        createTime: "2024-03-01 14:20:00",
        payTime: "2024-03-01 14:25:00",
        remark: "希望有专人指导",
      },
    ];
    total.value = 3;
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

// 重置搜索
const resetSearch = () => {
  searchForm.orderNo = "";
  searchForm.experience = "";
  searchForm.customer = "";
  searchForm.status = "";
  searchForm.dateRange = [];
  handleSearch();
};

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchData();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchData();
};

// 查看详情
const handleDetail = (row) => {
  currentOrder.value = row;
  detailVisible.value = true;
};

// 取消订单
const handleCancel = (row) => {
  ElMessageBox.confirm("确定要取消该订单吗？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      const res = await service.put(`/admin/experiences/orders/${row.orderNo}/cancel`);
      
      if (res.code === 200) {
        ElMessage.success("订单已取消");
        fetchData();
        if (detailVisible.value) {
          detailVisible.value = false;
        }
      } else {
        ElMessage.error(res.message || "取消失败");
      }
    } catch (error) {
      console.error("取消失败", error);
      ElMessage.error("取消失败");
    }
  });
};

// 完成订单
const handleComplete = (row) => {
  ElMessageBox.confirm("确定要将订单标记为已完成吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "info",
  }).then(async () => {
    try {
      const res = await service.put(`/admin/experiences/orders/${row.orderNo}/complete`);
      
      if (res.code === 200) {
        ElMessage.success("订单已完成");
        fetchData();
        if (detailVisible.value) {
          detailVisible.value = false;
        }
      } else {
        ElMessage.error(res.message || "操作失败");
      }
    } catch (error) {
      console.error("操作失败", error);
      ElMessage.error("操作失败");
    }
  });
};

// 导出数据
const exportData = () => {
  try {
    // 准备导出数据
    const exportItems = tableData.value.map(item => ({
      '订单号': item.orderNo,
      '体验项目': item.experience.title,
      '预约时间': item.bookingTime,
      '预约人': item.customer.name,
      '联系电话': item.customer.phone,
      '预约人数': item.quantity,
      '订单金额': item.amount,
      '订单状态': getStatusText(item.status),
      '下单时间': item.createTime,
      '支付时间': item.payTime || '-',
      '备注': item.remark || '-'
    }));
    
    // 创建工作簿和工作表
    const worksheet = XLSX.utils.json_to_sheet(exportItems);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, '体验订单列表');
    
    // 设置列宽
    const colWidth = [
      { wch: 20 }, // 订单号
      { wch: 30 }, // 体验项目
      { wch: 20 }, // 预约时间
      { wch: 10 }, // 预约人
      { wch: 15 }, // 联系电话
      { wch: 10 }, // 预约人数
      { wch: 10 }, // 订单金额
      { wch: 10 }, // 订单状态
      { wch: 20 }, // 下单时间
      { wch: 20 }, // 支付时间
      { wch: 30 }  // 备注
    ];
    worksheet['!cols'] = colWidth;
    
    // 导出Excel文件
    XLSX.writeFile(workbook, `体验订单列表_${new Date().toISOString().split('T')[0]}.xlsx`);
    
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出失败", error);
    ElMessage.error("导出失败");
  }
};

// 初始化
onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.orders-management {
  padding: 20px;
  background-color: var(--el-bg-color-page);
  min-height: calc(100vh - 40px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}

.search-form {
  background-color: var(--el-bg-color);
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

:deep(.el-table th) {
  background-color: var(--el-bg-color);
  font-weight: 600;
}

:deep(.el-table__row) {
  transition: background-color 0.3s ease;
}

:deep(.el-table__row:hover) {
  background-color: var(--el-color-primary-light-9) !important;
}

.experience-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.experience-image {
  width: 100px;
  height: 70px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.experience-image:hover {
  transform: scale(1.02);
}

.experience-detail {
  flex: 1;
  min-width: 0;
}

.experience-title {
  margin: 0 0 8px;
  font-size: 15px;
  font-weight: 500;
  color: var(--el-text-color-primary);
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.experience-time {
  margin: 0;
  font-size: 13px;
  color: var(--el-text-color-secondary);
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 12px;
  height: 24px;
  line-height: 24px;
}

:deep(.el-button--small) {
  padding: 6px 12px;
  font-size: 13px;
}

.pagination-container {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid var(--el-border-color-light);
  display: flex;
  justify-content: flex-end;
}

/* 优化对话框样式 */
:deep(.el-dialog) {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: 90vh;
  max-width: 90vw;
}

:deep(.el-dialog__body) {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
}

:deep(.el-dialog__header) {
  padding: 20px;
  margin: 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

:deep(.el-dialog__footer) {
  padding: 20px;
  margin: 0;
  border-top: 1px solid var(--el-border-color-lighter);
}

/* 订单详情样式 */
.order-detail {
  padding: 0 20px;
}

:deep(.el-descriptions) {
  margin-bottom: 24px;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
}

.detail-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .orders-management {
    padding: 12px;
  }

  .search-form {
    padding: 16px;
  }

  .experience-image {
    width: 80px;
    height: 60px;
  }

  .experience-title {
    font-size: 14px;
  }

  :deep(.el-dialog) {
    width: 90% !important;
  }
}

.empty-state {
  padding: 40px 0;
}

.empty-text {
  font-size: 16px;
  color: var(--el-text-color-secondary);
  margin-top: 10px;
}

.empty-subtext {
  font-size: 14px;
  color: var(--el-text-color-placeholder);
  margin-top: 5px;
}
</style>
